<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '',
  },
}
</route>

<template>
  <view class="">
    <view>
      <wd-message-box />
      <wd-toast />
      <wd-form ref="form" :model="model" :rules="rules">
        <wd-cell-group custom-class="group" title="车辆信息录入" :border="true">
          <wd-cell title="车身照片" title-width="100px" prop="carImageList">
            <wd-upload
              :file-list="model.carImageList"
              :limit="1"
              :upload-method="customCarImageUpload"
              @success="handleCarImageFileSuccess"
              @fail="handleCarImageFileFail"
            ></wd-upload>
          </wd-cell>
          <wd-cell title="车牌照片" title-width="100px" prop="licenseImageList">
            <wd-upload
              :file-list="model.licenseImageList"
              :limit="1"
              :upload-method="customLicenseImageUpload"
              @success="handleLicenseImageFileSuccess"
              @fail="handleLicenseImageFileFileFail"
            ></wd-upload>
          </wd-cell>
          <wd-input
            label="车牌号"
            label-width="100px"
            v-model="model.license_plate"
            placeholder="车牌号"
            disabled
          />
          <wd-input
            label="车辆类型"
            label-width="100px"
            v-model="model.vehicle_type"
            placeholder="请输入车辆类型"
          />

          <wd-input
            label="make"
            label-width="100px"
            v-model="model.make"
            placeholder="请输入品牌"
          />

          <wd-input
            label="model"
            label-width="100px"
            v-model="model.model"
            placeholder="请输入型号"
          />

          <wd-input
            label="color"
            label-width="100px"
            v-model="model.model"
            placeholder="请输入颜色"
          />

          <wd-input
            label="停车场"
            label-width="100px"
            v-model="model.parking_lot_info"
            placeholder="请输入停车场"
            disabled
          />
          <wd-input
            label="车位"
            label-width="100px"
            v-model="model.space_info"
            placeholder="请输入车位"
            disabled
          />
        </wd-cell-group>
        <view class="footer">
          <wd-button type="primary" size="large" @click="handleSubmit" block>提交</wd-button>
        </view>
      </wd-form>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { useToast } from 'wot-design-uni'
import { isArray } from 'wot-design-uni/components/common/util'
import { FormRules } from 'wot-design-uni/components/wd-form/types'
import { reactive, ref } from 'vue'
import { tingcheweiliebiaoVo, yonghutingche } from '@/api'
import { getEnvBaseUploadUrl } from '@/utils/index'
const form = ref(null)

const model = reactive<ModelData>({})

interface ModelData {
  /** 车身照片 */
  carImageList?: []
  /** 车牌照片 */
  licenseImageList?: []
  /** 主键 */
  car_id?: number
  /** 颜色 */
  color?: string
  /** 车牌号 */
  license_plate?: string
  /** 品牌 */
  make?: string
  /** 型号 */
  model?: string
  /** 停车场ID */
  parking_lot_id?: number
  parking_lot_info?: string
  /** 车位id */
  parking_space_id?: number
  /** 车位信息 */
  space_info?: string
  /** 车位编码 */
  code?: string
  /** 车辆图片 */
  picture?: string
  /** 用户id */
  user_id?: number
  /** 车辆类型 */
  vehicle_type?: string
}

const rules: FormRules = {
  couponName: [
    {
      required: true,
      pattern: /\d{6}/,
      message: '优惠券名称6个字以上',
      validator: (value) => {
        if (value) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请输入优惠券名称'))
        }
      },
    },
  ],
  fileList: [
    {
      required: true,
      message: '请选择活动图片',
      validator: (value) => {
        if (isArray(value) && value.length) {
          return Promise.resolve()
        } else {
          return Promise.reject(new Error('请选择活动图片'))
        }
      },
    },
  ],
}

const toast = useToast()

const handleCarImageFileSuccess = ({ file, fileList, formData }) => {
  if (fileList.length > 0) {
    model.carImageList = fileList
    const resp = fileList[0].response
    console.log('上传响应:', resp)
    const respJson = JSON.parse(resp)
    // response: "{"code":200,"msg":"成功","data":{"id":155,"cid":0,"type":10,"name":"IXTHvHO0OUNn23b148f8166276880b99085fb0754833.png","url":"image/20250527/0bc80575-50bf-40e7-9bbb-5f5d67fdd654.png","uri":"http://192.168.1.14:8084/api/uploads/image/20250527/0bc80575-50bf-40e7-9bbb-5f5d67fdd654.png"},"show":0}"
    if (respJson && respJson.code === 200) {
      // 假设返回的文件对象有url或path属性
      model.picture = respJson.data.url
    } else {
      uni.showToast({
        title: '上传失败，请重试',
        icon: 'none',
      })
      model.picture = ''
    }
  } else {
    model.picture = ''
  }
}

const handleCarImageFileFail = ({ error, file, formData }) => {
  console.error('上传失败:', error, file)
  model.carImageList = []
  model.picture = ''
}

const customCarImageUpload = async (file, formData, options) => {
  const url = getEnvBaseUploadUrl()
  console.log('自定义上传url:', url)
  const uploadTask = uni.uploadFile({
    url,
    header: options.header,
    name: options.name,
    fileName: options.name,
    fileType: options.fileType,
    formData,
    filePath: file.url,
    success(res) {
      if (res.statusCode === options.statusCode) {
        // 设置上传成功
        options.onSuccess(res, file, formData)
      } else {
        // 设置上传失败
        options.onError({ ...res, errMsg: res.errMsg || '' }, file, formData)
      }
    },
    fail(err) {
      // 设置上传失败
      options.onError(err, file, formData)
    },
  })
  // 设置当前文件加载的百分比
  uploadTask.onProgressUpdate((res) => {
    options.onProgress(res, file)
  })
}

const handleLicenseImageFileSuccess = ({ file, fileList, formData }) => {
  if (fileList.length > 0) {
    model.carImageList = fileList
    const resp = fileList[0].response
    console.log('上传响应:', resp)
    const respJson = JSON.parse(resp)
    // response: "{"code":200,"msg":"成功","data":{"id":155,"cid":0,"type":10,"name":"IXTHvHO0OUNn23b148f8166276880b99085fb0754833.png","url":"image/20250527/0bc80575-50bf-40e7-9bbb-5f5d67fdd654.png","uri":"http://192.168.1.14:8084/api/uploads/image/20250527/0bc80575-50bf-40e7-9bbb-5f5d67fdd654.png"},"show":0}"
    if (respJson && respJson.code === 200) {
      // 假设返回的文件对象有url或path属性
      model.picture = respJson.data.url
    } else {
      uni.showToast({
        title: '上传失败，请重试',
        icon: 'none',
      })
      model.picture = ''
    }
  } else {
    model.picture = ''
  }
}

const handleLicenseImageFileFileFail = ({ error, file, formData }) => {
  console.error('上传失败:', error, file)
  model.carImageList = []
  model.picture = ''
}

const customLicenseImageUpload = async (file, formData, options) => {
  const url = getEnvBaseUploadUrl()
  console.log('自定义上传url:', url)
  const uploadTask = uni.uploadFile({
    url,
    header: options.header,
    name: options.name,
    fileName: options.name,
    fileType: options.fileType,
    formData,
    filePath: file.url,
    success(res) {
      if (res.statusCode === options.statusCode) {
        // 设置上传成功
        options.onSuccess(res, file, formData)
      } else {
        // 设置上传失败
        options.onError({ ...res, errMsg: res.errMsg || '' }, file, formData)
      }
    },
    fail(err) {
      // 设置上传失败
      options.onError(err, file, formData)
    },
  })
  // 设置当前文件加载的百分比
  uploadTask.onProgressUpdate((res) => {
    options.onProgress(res, file)
  })
}

onLoad((options) => {
  console.log('车位id', options.parkingId)

  // 页面加载时的逻辑
  console.log('页面加载')
})
</script>

<style lang="scss" scoped>
.inline-txt {
  display: inline-block;
  margin: 0 8px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
  vertical-align: middle;
}
:deep(.group) {
  margin-top: 12px;
}
.tip {
  margin: 10px 15px 21px;
  font-size: 12px;
  color: #999;
}
.footer {
  padding: 0 25px 21px;
}
:deep(.label-class) {
  font-size: 12px !important;
  color: #999 !important;
}
</style>
